package com.bsj.power.pls.config.net.netty.common.timer;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.bsj.power.pls.config.net.netty.TcpClientNet;
import com.bsj.power.pls.config.net.netty.common.client.RTKTcpClientConstant;
import lombok.extern.slf4j.Slf4j;

/**
 * @author yinhao
 * @version 1.0
 * @description 定时重启tcp客户端线程
 * @date 2024/10/25
 */
@Slf4j
public class ScheduledResetThread {

    public boolean isRunning = true;
    public static TcpClientNet tcpClientNet = null;
    private static Thread thread;

    public void doStart() {
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (isRunning) {
                    try {
                        if (tcpClientNet == null) {
                            tcpClientNet = new TcpClientNet(RTKTcpClientConstant.ip, RTKTcpClientConstant.port);
                            tcpClientNet.initClient();
                            tcpClientNet.doConnect();
                        } else {
                            //停止后重连
                            tcpClientNet.stop();
                            tcpClientNet.initClient();
                            tcpClientNet.doConnect();
                        }
                        Thread.sleep(1 * 60 * 1000);
                    } catch (Exception e) {
                        log.error(ExceptionUtil.getMessage(e));
                        return;
                    }
                }
            }
        });
        log.info("初始化tcp客户端线程...");
        thread.start();
    }

    public void doStop() {
        isRunning = false;
        if (thread != null) {
            thread.interrupt();
        }
    }
}
